/**
 * @Project : algorithm-learning
 * @Author : Ruoyu Wang
 * @User : Momenta
 * @DateTime : 2024/4/17 16:07
 */

struct ListNode {
    int val;
    ListNode *next;

    ListNode() : val(0), next(nullptr) {}

    ListNode(int x) : val(x), next(nullptr) {}

    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *h = new ListNode(-1, head);
        ListNode *p = h;
        ListNode *s = h;

        for (int i = 0; i < n; ++i) {
            s = s->next;
        }

        while (s->next == nullptr) {
            p = p->next;
            s = s->next;
        }

        p->next = p->next->next;

        return h->next;
    }
};